<template>
  <view class="container">
    <view class="header">
      <view class="header-left" @tap="navigateBack">
        <text class="back-icon">←</text>
      </view>
      <text class="header-title">{{ currentScaleName }}</text>
      <view class="header-right"></view>
    </view>

    <view class="scale-container">
      <!-- 量表进度 -->
      <view class="progress-bar">
        <view class="progress-item" :class="{ active: currentScaleIndex >= 0 }">
          <text class="progress-text">抑郁量表</text>
        </view>
        <view class="progress-item" :class="{ active: currentScaleIndex >= 1 }">
          <text class="progress-text">焦虑量表</text>
        </view>
        <view class="progress-item" :class="{ active: currentScaleIndex >= 2 }">
          <text class="progress-text">躁狂量表</text>
        </view>
      </view>

      <!-- 量表内容 -->
      <view class="scale-content" v-if="currentScale">
        <view class="scale-title">{{ currentScale.title }}</view>
        <view class="scale-description">{{ currentScale.description }}</view>
        
        <!-- 量表题目 -->
        <view class="questions-container">
          <view v-for="(question, index) in currentScale.questions" :key="index" class="question-item">
            <view class="question-title">{{ index + 1 }}. {{ question.title }}</view>
            <view class="question-options">
              <view 
                v-for="(option, optionIndex) in question.options" 
                :key="optionIndex"
                class="option-item"
                :class="{ active: answers[index] === optionIndex }"
                @tap="selectAnswer(index, optionIndex)"
              >
                <text class="option-text">{{ option }}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 操作按钮 -->
        <view class="action-buttons">
          <button v-if="currentScaleIndex > 0" class="prev-btn" @tap="prevScale">上一量表</button>
          <button 
            class="next-btn" 
            @tap="nextScale"
            :disabled="!canProceed"
          >
            {{ currentScaleIndex < scales.length - 1 ? '下一量表' : '完成评估' }}
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { submitHamd17, submitHama, submitYmrs } from '../../../utils/api/doctor.js';

export default {
  data() {
    return {
      assessmentId: '',
      patientUserId: '',
      currentScaleIndex: 0,
      answers: {},
      scales: [
        {
          type: 'hamd',
          title: '汉密尔顿抑郁量表 (HAMD)',
          description: '请根据患者最近一周的情况进行评分',
          questions: [
            { title: '抑郁情绪', options: ['无', '只在问到时才诉述', '在访谈中自发地表达', '不用言语也可以从表情、姿势、声音或欲哭中流露出这种情绪', '病人的自发言语和非语言表达（表情、动作）几乎完全表现为这种情绪'] },
            { title: '有罪感', options: ['无', '责备自己，感到自己已连累他人', '认为自己犯了罪，或反复思考以往的过失或错误', '认为目前的疾病是对自己错误的惩罚，或有罪恶妄想', '罪恶妄想伴有指责或威胁性幻觉'] },
            { title: '自杀', options: ['无', '觉得活着没有意义', '希望自己已经死去，或常想到与死有关的事', '消极观念（自杀念头）', '有严重自杀行为'] },
            { title: '入睡困难', options: ['无', '主诉有入睡困难，上床半小时后仍不能入睡', '主诉每晚均有入睡困难'] },
            { title: '睡眠不深', options: ['无', '睡眠浅，多恶梦', '半夜（晚上12点以前）曾醒来（不包括上厕所）'] },
            { title: '早醒', options: ['无', '有早醒，比平时早醒1小时，但能重新入睡', '早醒后无法重新入睡'] },
            { title: '工作和兴趣', options: ['无', '提问时才诉述', '自发地直接或间接表达对活动、工作或学习失去兴趣', '活动时间减少或成效下降', '因目前的疾病而停止工作'] },
            { title: '迟缓', options: ['无', '精神检查中发现轻度迟缓', '精神检查中发现明显迟缓', '精神检查进行困难', '完全不能回答问题（木僵）'] },
            { title: '激越', options: ['无', '检查时有些心神不定', '明显心神不定或小动作多', '不能静坐，检查中曾起立', '搓手、咬手指、扯头发、咬嘴唇'] },
            { title: '精神性焦虑', options: ['无', '问及时才诉述', '自发地表达', '表情和言谈流露出明显忧虑', '明显惊恐'] },
            { title: '躯体性焦虑', options: ['无', '轻度', '中度，有肯定的上述症状', '重度，上述症状严重，影响生活或需要处理', '严重影响生活和活动'] },
            { title: '胃肠道症状', options: ['无', '食欲减退，但不需他人鼓励便自行进食', '进食需他人催促或请求和需要应用泻药或助消化药'] },
            { title: '全身症状', options: ['无', '四肢、背部或颈部沉重感，背痛、头痛、肌肉疼痛，全身乏力或疲倦', '症状明显'] },
            { title: '性症状', options: ['无', '轻度', '重度', '不能肯定，或该项对被评者不适合（不计入总分）'] },
            { title: '疑病', options: ['无', '对身体过分关注', '反复考虑健康问题', '有疑病妄想', '伴幻觉的疑病妄想'] },
            { title: '体重减轻', options: ['无', '一周内体重减轻超过0.5公斤', '一周内体重减轻超过1公斤'] },
            { title: '自知力', options: ['知道自己有病，表现为忧郁', '知道自己有病，但归咎伙食太差，环境问题，工作过忙，病毒感染或需要休息', '完全否认有病'] }
          ]
        },
        {
          type: 'hama',
          title: '汉密尔顿焦虑量表 (HAMA)',
          description: '请根据患者最近一周的情况进行评分',
          questions: [
            { title: '焦虑心境', options: ['无', '轻微', '中等', '严重', '极重'] },
            { title: '紧张', options: ['无', '轻微', '中等', '严重', '极重'] },
            { title: '害怕', options: ['无', '轻微', '中等', '严重', '极重'] },
            { title: '失眠', options: ['无', '轻微', '中等', '严重', '极重'] },
            { title: '认知功能', options: ['无', '轻微', '中等', '严重', '极重'] },
            { title: '抑郁心境', options: ['无', '轻微', '中等', '严重', '极重'] },
            { title: '躯体性肌肉症状', options: ['无', '轻微', '中等', '严重', '极重'] },
            { title: '躯体性感觉症状', options: ['无', '轻微', '中等', '严重', '极重'] },
            { title: '心血管系统症状', options: ['无', '轻微', '中等', '严重', '极重'] },
            { title: '呼吸系统症状', options: ['无', '轻微', '中等', '严重', '极重'] },
            { title: '胃肠道症状', options: ['无', '轻微', '中等', '严重', '极重'] },
            { title: '泌尿生殖系统症状', options: ['无', '轻微', '中等', '严重', '极重'] },
            { title: '自主神经症状', options: ['无', '轻微', '中等', '严重', '极重'] },
            { title: '行为表现', options: ['无', '轻微', '中等', '严重', '极重'] }
          ]
        },
        {
          type: 'ymrs',
          title: '杨氏躁狂评定量表 (YMRS)',
          description: '请根据患者最近一周的情况进行评分',
          questions: [
            { title: '情绪高涨', options: ['无', '轻微', '中等', '严重', '极重'] },
            { title: '活动增多', options: ['无', '轻微', '中等', '严重', '极重'] },
            { title: '睡眠减少', options: ['无', '轻微', '中等', '严重', '极重'] },
            { title: '易激惹', options: ['无', '轻微', '中等', '严重', '极重'] },
            { title: '言语速度', options: ['无', '轻微', '中等', '严重', '极重'] },
            { title: '言语迫促', options: ['无', '轻微', '中等', '严重', '极重'] },
            { title: '思维内容', options: ['无', '轻微', '中等', '严重', '极重'] },
            { title: '夸大观念', options: ['无', '轻微', '中等', '严重', '极重'] },
            { title: '注意力分散', options: ['无', '轻微', '中等', '严重', '极重'] },
            { title: '敌意', options: ['无', '轻微', '中等', '严重', '极重'] },
            { title: '夸大观念严重程度', options: ['无', '轻微', '中等', '严重', '极重'] }
          ]
        }
      ]
    }
  },
  computed: {
    currentScale() {
      return this.scales[this.currentScaleIndex];
    },
    currentScaleName() {
      return this.currentScale ? this.currentScale.title : '';
    },
    canProceed() {
      if (!this.currentScale) return false;
      return this.currentScale.questions.every((_, index) => this.answers[index] !== undefined);
    }
  },
  onLoad(options) {
    if (options.assessmentId && options.patientUserId) {
      this.assessmentId = options.assessmentId;
      this.patientUserId = options.patientUserId;
    }
  },
  methods: {
    // 返回上一页
    navigateBack() {
      uni.navigateBack();
    },
    
    // 选择答案
    selectAnswer(questionIndex, optionIndex) {
      this.$set(this.answers, questionIndex, optionIndex);
    },
    
    // 上一量表
    prevScale() {
      if (this.currentScaleIndex > 0) {
        this.currentScaleIndex--;
        this.answers = {};
      }
    },
    
    // 下一量表或完成
    async nextScale() {
      if (!this.canProceed) {
        uni.showToast({
          title: '请完成所有题目',
          icon: 'none'
        });
        return;
      }
      
      // 保存当前量表答案
      await this.saveCurrentScale();
      
      if (this.currentScaleIndex < this.scales.length - 1) {
        this.currentScaleIndex++;
        this.answers = {};
      } else {
        // 完成所有量表
        uni.showToast({
          title: '评估完成',
          icon: 'success'
        });
        
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      }
    },
    
    // 保存当前量表
    async saveCurrentScale() {
      try {
        const scaleData = {};
        const currentScale = this.currentScale;
        
        // 构造量表数据
        currentScale.questions.forEach((question, index) => {
          const answer = this.answers[index];
          if (answer !== undefined) {
            scaleData[`item${index + 1}_${this.getFieldName(currentScale.type, index)}`] = answer;
          }
        });
        
        // 根据量表类型调用不同的API
        let response;
        if (currentScale.type === 'hamd') {
          response = await submitHamd17(this.assessmentId, scaleData);
        } else if (currentScale.type === 'hama') {
          response = await submitHama(this.assessmentId, scaleData);
        } else if (currentScale.type === 'ymrs') {
          response = await submitYmrs(this.assessmentId, scaleData);
        }
        
        if (response.code === 200) {
          console.log(`${currentScale.title} 保存成功`);
        } else {
          uni.showToast({
            title: '保存失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('保存量表失败:', error);
        uni.showToast({
          title: '保存失败',
          icon: 'none'
        });
      }
    },
    
    // 获取字段名
    getFieldName(scaleType, index) {
      const fieldNames = {
        hamd: ['depression', 'guilt', 'suicide', 'sleep_initial', 'sleep_middle', 'sleep_late', 'activity', 'retardation', 'agitation', 'anxiety_psychic', 'anxiety_somatic', 'somatic_symptoms', 'general_somatic', 'genital', 'hypochondriasis', 'weight', 'insight'],
        hama: ['irritability', 'tension', 'fears', 'insomnia', 'cognition', 'depressed_mood', 'somatic_muscle', 'somatic_sensory', 'cardiovascular', 'respiratory', 'gastrointestinal', 'genitourinary', 'autonomic', 'behavior'],
        ymrs: ['mood_elevated', 'activity', 'sleep', 'irritability', 'speech_rate', 'speech_pressured', 'thought_content', 'grandiosity', 'distractibility', 'hostility', 'grandiosity_severity']
      };
      
      return fieldNames[scaleType] ? fieldNames[scaleType][index] : `item${index + 1}`;
    }
  }
}
</script>

<style scoped>
.container {
  padding-bottom: 80rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
  background-color: #FF7A45;
  padding: 0 28rpx;
  box-shadow: 0 2rpx 10rpx rgba(255, 122, 69, 0.3);
}

.header-left {
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background-color 0.2s;
}

.header-left:active {
  background-color: rgba(255, 255, 255, 0.2);
}

.back-icon {
  color: #fff;
  font-size: 40rpx;
  font-weight: bold;
}

.header-title {
  color: #fff;
  font-size: 36rpx;
  font-weight: bold;
}

.header-right {
  width: 40rpx;
}

.scale-container {
  padding: 30rpx;
}

.progress-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 40rpx;
  background: #fff;
  padding: 20rpx;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
}

.progress-item {
  flex: 1;
  text-align: center;
  padding: 15rpx;
  border-radius: 8rpx;
  transition: all 0.3s ease;
}

.progress-item.active {
  background-color: #FF7A45;
  color: #fff;
}

.progress-text {
  font-size: 24rpx;
  color: #666;
}

.progress-item.active .progress-text {
  color: #fff;
}

.scale-content {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
}

.scale-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 15rpx;
}

.scale-description {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 40rpx;
  line-height: 1.5;
}

.questions-container {
  margin-bottom: 40rpx;
}

.question-item {
  margin-bottom: 40rpx;
  padding-bottom: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.question-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.question-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  line-height: 1.4;
}

.question-options {
  display: flex;
  flex-direction: column;
  gap: 15rpx;
}

.option-item {
  background: #f8f8f8;
  border: 2rpx solid #e8e8e8;
  border-radius: 8rpx;
  padding: 20rpx;
  transition: all 0.3s ease;
}

.option-item.active {
  background-color: #fff5f0;
  border-color: #FF7A45;
}

.option-text {
  font-size: 26rpx;
  color: #333;
  line-height: 1.4;
}

.action-buttons {
  display: flex;
  gap: 20rpx;
  margin-top: 40rpx;
}

.prev-btn, .next-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
  font-weight: bold;
}

.prev-btn {
  background-color: #f0f0f0;
  color: #666;
}

.next-btn {
  background-color: #FF7A45;
  color: #fff;
}

.next-btn:disabled {
  background-color: #ccc;
  color: #999;
}
</style>
